package com.hst.capacity.facade.handler;

import cn.smartravel.baidu.aip.AipException;
import com.hst.capacity.domain.enums.Rep;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.response.DefaultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {

    /**
     * 处理Request参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DefaultVO<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) {
        log.error("[methodArgumentNotValidExceptionExceptionHandler]", ex);
        String errorMessage = "";
        if (ex.getBindingResult().getErrorCount() > 0)
            errorMessage = (String) ex.getBindingResult().getFieldErrors()
                    .stream().map(m -> m.getDefaultMessage())
                    .collect(Collectors.joining(" | "));

        return DefaultVO.error(Rep.BAD_REQUEST.getCode(), String.format("入参校验失败: %s", errorMessage));
    }

    /**
     * 处理业务异常 BusinessException
     */
    @ExceptionHandler(value = DataAccessException.class)
    public DefaultVO<?> dataAccessExceptionHandler(DataAccessException ex) {
        log.info("[dataAccessException]", ex);
        return DefaultVO.error(Rep.DATA_ACCESS_EXCEPTION.getCode(), String.format("数据存储异常: %s", ex.getMessage()));
    }

    /**
     * 处理业务异常 BusinessException
     */
    @ExceptionHandler(value = BusinessException.class)
    public DefaultVO<?> businessExceptionHandler(BusinessException ex) {
        log.info("[businessExceptionHandler]", ex);
        return DefaultVO.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理百度AIP异常 AipException
     */
    @ExceptionHandler(value = AipException.class)
    public DefaultVO<?> aipExceptionHandler(AipException ex) {
        log.info("[aipExceptionHandler]", ex);
        return DefaultVO.error(ex.getCode(), ex.getMessage());
    }

}
